//
//  AppDelegateExtension.swift
//  DianXia
//
//  Created by you&me on 2017/12/18.
//  Copyright © 2017年 you&me. All rights reserved.
//

import Foundation

extension AppDelegate {

    //注册本地推送
    func requestAuthor() {
        let setting = UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)
        UIApplication.shared.registerUserNotificationSettings(setting)
    }
//添加定时器
    func addTimer()  {
        if locationTimer == nil {
            if #available(iOS 10.0, *) {
                locationTimer = Timer(timeInterval: 10*60, repeats: true, block: { (timer) in
                    self.uploadLocation()
                })
            } else {
                locationTimer = Timer.scheduledTimer(timeInterval: 10, target: self, selector: #selector(uploadLocation), userInfo: nil, repeats: true)
            }
            CFRunLoopAddTimer(CFRunLoopGetMain(), locationTimer, CFRunLoopMode.commonModes)
            locationTimer?.fire()
            //  CFRunLoopAddTimer(CFRunLoopGetCurrent(), cyTimer, CFRunLoopMode.commonModes) 也可以
        }
    }

    // 上传当前位置
    @objc func uploadLocation() {
        let lng = UserManager.shareManager.lng ?? ""
        let lat = UserManager.shareManager.lat ?? ""

        provider.rx.request(.synPositionRequest(mobile: UserManager.shareManager.userMobile ?? "", position: "\(lng)，\(lat)", type: UserManager.shareManager.business ?? ""))
            .asObservable()
            .retry(3)
            .mapModel(LocationModel.self)
            .subscribe(onNext: { (model) in
                if model.msg == "success" {
                    UserTasks.share.tasks = model.result?.tasks ?? [BCTask]()
                    if UserTasks.share.tasks.count > 0{
                        //清除本地进行的 并且添加新的
                        UserActivingTasks.share.tasks.removeAll()
                        for activingTask in UserTasks.share.tasks {
                            if activingTask.progress == "2" {
                               UserActivingTasks.share.tasks.append(activingTask)
                            }
                        }
                    // 后续执行
                      self.tasksThen()
                     }
                  }
              })
            .disposed(by: dispose)
    }
   // 获取任务列表之后的执行
    func tasksThen() {
        //如果程序是在后台 发送本地通知
        if UIApplication.shared.applicationState == .background {
            let localNoti = UILocalNotification()
            localNoti.alertBody = "您有新的任务，请注意查收!"
            // 通知的触发时间，例如即刻起
            let fireDate = NSDate().addingTimeInterval(1)
            localNoti.fireDate = fireDate as Date
            // 设置时区
            localNoti.timeZone = NSTimeZone.default
            //获取所有的本地应用
            let locals = UIApplication.shared.scheduledLocalNotifications
            localNoti.applicationIconBadgeNumber = locals?.count ?? 0 + 1
            localNoti.userInfo = ["info": UserTasks.share.tasks]
            // 添加通知到系统队列中，系统会在指定的时间触发
            UIApplication.shared.scheduleLocalNotification(localNoti)
        }else{
            //直接进入任务界面
            let vc = UIStoryboard.viewController(from: .Home, viewControllerClass: TasksVC.self)
            vc.taskType = .AllTask
            UIApplication.shared.delegate?.window??.rootViewController = vc

        }
    }

    func removeTimer() {
        locationTimer?.invalidate()
        locationTimer = nil
    }
}

//单利保存的任务信息
class UserTasks {
    static let share = UserTasks()
    var tasks = [BCTask]()
}

//单利保存进行中的任务信息
class UserActivingTasks {
    static let share = UserActivingTasks()
    var tasks = [BCTask]()
}

struct LocationModel: HandyJSON {
    var msg: String?
    var result: TasksModel?
}
struct TasksModel: HandyJSON {
    var describe: String?
    var tasks: [BCTask]?
}
struct BCTask: HandyJSON{
    var code: String?
    var address: String?
    var type: String?
    var progress: String? //1是新的 2 表示进行中
    var no: Int?
    var describe: String?

}

